<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>西瓜聊天</title>
    <style>
        .chat-container {
            width: 400px;
            height: 680px;
            border: 1px solid #ccc;
            margin: 50px auto;
            display: flex;
            flex-direction: column;
            font-family: Arial, sans-serif;
        }

        .chat-header {
            padding: 10px;
            background-color: #007bff;
            color: white;
            text-align: center;
            font-weight: bold;
        }

        .chat-users {
            padding: 10px;
            border-bottom: 1px solid #ccc;
            background-color: #f1f1f1;
            display: flex;
            gap: 10px;
        }

        .chat-users select {
            flex: 1;
            padding: 5px;
        }

        .chat-users button {
            padding: 5px 10px;
            color: white;
            border: none;
            cursor: pointer;
        }

        .chat-users .online {
            background-color: #28a745; /* 上线绿色 */
        }

        .chat-users .offline {
            background-color: #dc3545; /* 下线红色 */
        }

        .chat-messages {
            flex: 1;
            padding: 10px;
            overflow-y: auto;
            background-color: #f9f9f9;
        }

        .chat-input {
            display: flex;
            border-top: 1px solid #ccc;
        }

        .chat-input input {
            flex: 1;
            padding: 10px;
            border: none;
            outline: none;
        }

        .chat-input button {
            padding: 10px 20px;
            border: none;
            background-color: #007bff;
            color: white;
            cursor: pointer;
        }

        .message {
            margin-bottom: 10px;
        }

        .message.you {
            text-align: right;
            color: blue;
        }

        .message.other {
            text-align: left;
            color: green;
        }

        .status-bar {
            font-size: 12px;
            padding: 5px 10px;
            color: gray;
            background-color: #f5f5f5;
            border-top: 1px solid #ccc;
        }

        .refresh-btn {
            padding: 5px 10px;
            background-color: #17a2b8;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s ease;
        }

        .refresh-btn:hover {
            background-color: #138496;
        }
    </style>
</head>
<body>

<div class="chat-container">
    <div class="chat-header">西瓜聊天</div>

    <div class="chat-users">
        <select id="userSelect">
            <option value="user_a">用户 A</option>
            <option value="user_b">用户 B</option>
            <option value="user_c">用户 C</option>
        </select>
        <button id="statusBtn" class="online" onclick="toggleConnection()">上线</button>
        <button class="refresh-btn" onclick="fetchOnlineUsers()">刷新在线用户</button>
    </div>

    <div class="chat-messages" id="chatMessages"></div>

    <div class="chat-input">
        <input type="text" id="messageInput" placeholder="输入消息..." />
        <button onclick="sendMessage()">发送</button>
    </div>

    <div class="status-bar" id="statusBar">
        当前状态：未连接 ｜ 我的ID：<span id="myUserId">未分配</span>
    </div>

</div>

<script>
    let socket = null;
    let userId = null;
    let receiverId = null;

    const messagesDiv = document.getElementById('chatMessages');
    const input = document.getElementById('messageInput');
    const userSelect = document.getElementById('userSelect');
    const statusBar = document.getElementById('statusBar');
    const statusBtn = document.getElementById('statusBtn');

    window.onload = function () {
        fetchOnlineUsers();
    };


    // 切换连接状态
    function toggleConnection() {
        if (socket && socket.readyState === WebSocket.OPEN) {
            disconnect();  // 断开连接
        } else {
            connect();  // 建立连接
        }
    }

    // WebSocket 连接
    function connect() {
        // 生成用户ID
        userId = Math.floor(Math.random() * 100) + 1;
        receiverId = userSelect.value;  // 获取接收人ID（可以通过选择框来选择）

        const userIdElement = document.getElementById('myUserId');
        if (userIdElement) {
            userIdElement.textContent = userId;  // 更新用户ID显示
        }

        const wsUrl = `ws://localhost:8090/client/connect/${userId}`; // 替换为你服务端的实际 WebSocket 地址
        socket = new WebSocket(wsUrl);

        socket.onopen = () => {
            statusBar.textContent = `当前状态：已连接 ｜ 我的ID：${userId}`;
            statusBtn.textContent = '下线';
            statusBtn.classList.remove('online');
            statusBtn.classList.add('offline');
            logSystem(`已连接到服务器，用户ID: ${userId}`);
        };

        socket.onmessage = (event) => {
            const reply = document.createElement('div');
            reply.className = 'message other';
            reply.textContent = event.data;
            messagesDiv.appendChild(reply);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        };

        socket.onclose = () => {
            // 断开连接时
            statusBar.textContent = '当前状态：连接已关闭 ｜ 我的ID：';

            // 确保 ID 显示部分存在
            const userIdElement = document.getElementById('myUserId');
            if (userIdElement) {
                userIdElement.textContent = '未分配';  // 清空用户ID
            }

            statusBtn.textContent = '上线';
            statusBtn.classList.remove('offline');
            statusBtn.classList.add('online');
            logSystem('连接已关闭');
        };

        socket.onerror = () => {
            statusBar.textContent = '当前状态：连接错误 ｜ 我的ID：';

            // 确保 ID 显示部分存在
            const userIdElement = document.getElementById('myUserId');
            if (userIdElement) {
                userIdElement.textContent = '未分配';  // 清空用户ID
            }

            logSystem('连接出现错误');
        };
    }

    // WebSocket 断开
    function disconnect() {
        if (socket) {
            socket.close();
        }
        // 确保在断开连接后能够清空状态
        const userIdElement = document.getElementById('myUserId');
        if (userIdElement) {
            userIdElement.textContent = '未分配';  // 清空用户ID
        }
    }

    // WebSocket 断开
    function disconnect() {
        if (socket) {
            socket.close();
        }
    }

    // 发送消息
    function sendMessage() {
        const text = input.value.trim();
        if (!text || !socket || socket.readyState !== WebSocket.OPEN) return;
        const currentReceiverId = userSelect.value;

        // 封装消息对象
        const message = {
            senderId: userId,
            receiverId: currentReceiverId,
            message: text
        };

        socket.send(JSON.stringify(message));

        // 显示自己的消息
        const myMsg = document.createElement('div');
        myMsg.className = 'message you';
        myMsg.textContent = `[我] ${text}`;
        messagesDiv.appendChild(myMsg);
        messagesDiv.scrollTop = messagesDiv.scrollHeight;

        input.value = '';
    }

    // 系统日志
    function logSystem(message) {
        const log = document.createElement('div');
        log.className = 'message system';
        log.style.color = 'gray';
        log.textContent = `系统提示：${message}`;
        messagesDiv.appendChild(log);
    }

    // 获取在线用户并渲染到 select（POST 版本）
    async function fetchOnlineUsers() {
        try {
            const response = await fetch('http://localhost:8090/center/center/getOnlineId', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({})  // 如果接口需要传参数，可以在这里补上
            });

            const onlineUsers = await response.json().then(data => data.data);

            // 清除原有选项，保留默认几个用户
            userSelect.innerHTML = `
            <option value="user_a">用户 A</option>
            <option value="user_b">用户 B</option>
            <option value="user_c">用户 C</option>
        `;

            // 添加从接口获取的在线用户
            onlineUsers.forEach(id => {
                const option = document.createElement('option');
                option.value = id;
                option.textContent = `在线用户 ${id}`;
                userSelect.appendChild(option);
            });

        } catch (err) {
            console.error('获取在线用户失败', err);
            logSystem('获取在线用户失败');
        }
    }

</script>

</body>
</html>
